<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <style>
        .card {
            width: 800px;
            height: 400px;
            background-color: #f2f2f2;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 2px 2px 10px #ccc;
            margin: 50px auto;
        }

        .card-header {
            background-color: #333 !important;
            color: #fff;
            padding: 20px !important;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
            text-align: center;
        }

        .input-container {
            width: 100%;
            height: 37px;
            padding: 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .input-text {
            width: 100%;
            height: 100%;
            padding: 10px;
            font-size: 16px;
            border: none;
            outline: none;
        }

        .path-rule-input {
            display: flex;
            align-items: center;
        }

        .path-rule-input span {
            cursor: pointer;
            position: relative;
            margin-right: 10px;
        }

        .path-rule-input span:hover .tooltips {
            display: block;
        }

        .tooltips {
            width: 350px;
            position: absolute;
            left: 20px;
            top: -7px;
            border: 1px solid gray;
            z-index: 10;
            background: #fff;
            padding: 10px;
            display: none;
        }

        #fileProgress {
            margin-left: 30px;
        }
    </style>
    <title>上传文件</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">上传文件到OBS</h5>
            </div>
            <div class="card-body">
                <!-- <form action="#" method="post" enctype="multipart/form-data"> -->
                <label>输入obs目标路径</label><br/>
                <div class="input-container path-rule-input">
                    <input
                        type="text"
                        class="input-text"
                        placeholder="请输入目标路径"
                        id="path"
                        value="/"
                        onblur="handleBlur()"
                />
                    <span>?
              <div class="tooltips">
                <h6>路径规则：</h6>
                <ol style="padding-left: 15px">
                  <li>根路径（默认）：‘/’</li>
                  <li>根路径下a文件夹：‘/a’ 或 ‘/a/’ 或 ‘a’ 或 ‘a/’</li>
                  <li>多级目录：‘a/b’ 或 ‘/a/b’ 或 ‘/a/b/’ 或 ‘a/b/’</li>
                  <li>
                    路径可包含：中文汉字、大小写字母、数字、下划线（_）、中划线（-）和（/）
                  </li>
                </ol>
              </div>
            </span>
                </div>
                <br/>
                <div class="form-group">
                    <label for="file">选择需要上传的文件（单个文件不大于5G，每次最多选择50个文件）</label>
                    <div class="custom-file">
                        <input
                            type="file"
                            class="custom-file-input"
                            id="file"
                            name="file"
                            multiple
                            onchange="change()"
                    />
                        <label class="custom-file-label" for="file">选择文件</label>
                    </div>
                </div>
                <div>
                    <span>上传进度(已完成/总数)：</span>
                    <span id="progress"></span>
                    <span id="fileProgress" >  </span>
                </div>
                <br/>
                <button class="btn btn-primary" onclick="submit()">
                <i class="fas fa-upload"></i> 上传
            </button>
            </div>
        </div>
    </div>
</body>
<script>
    let p = path
    let files = []
    let url

    function handleBlur() {
        file.disabled = true
         if (!p.value) {
            alert('路径不能为空')
            return false
          }
          // 根据正则匹配路径
          if (
            !/([\u4E00-\u9FA5AA-Za-z0-9_/-])/.test(p.value) ||
            p.value.includes('//')
          ) {
            // 消息提示，路径规则错误
            alert('路径规则错误')
            return false
          }
          file.disabled = false
    }

    function change(e) {
        if(file.files.length > 50){
            alert('最多选择50个文件！请重新选择')
            num = 0
            files.length = 0
            return false
        }
        let flag =  Array.from(file.files).some(file => {
            return file.size > 5*1024*1024*1024
        })
        if(flag){alert('存在文件大于5G，请重新选择！')
        num = 0
            files.length = 0
            return false
        }
      // 根据名称和p获取url
      for (val of file.files) {
        let obj = {
          f: val
        }
        axios
          .get(`/upload_file/signed_url?fileName=${val.name}&upload_path=${p.value}`)
          .then((res) => {
            if (res.status === 200) {
              obj.url = res.data
            }
          })
        files.push(obj)
      }
      progress.innerHTML = num + '/' + files.length
    }
    let num = 0
    function submit() {
        if(files.length <= 0) {
            alert('请先选择文件')
            return false
       }
             uploadIt(num)
    }

    function uploadIt(num) {
    progress.innerHTML = num + '/' + files.length
    console.log(num,files.length)
    if(num >= files.length){
    fileProgress.innerHTML = ''
    files.length = 0;
     return false}
   fileProgress.innerHTML =  '当前上传文件(<span id="currentFileProgress"></span>)：<span id="currentFile"></span>'
    if (files[num].size > 5 * 1024 * 1024 * 1024) {
              // 消息提示文件过大
              alert('文件超过最大限制5G')
              return false
            }
            // url和file上传文件
        axios
          .request({
            method: 'put',
            url: files[num].url,
            withCredentials: false,
            headers: {
              'Content-Type': 'application/octet-stream',
              Host: files[num].url.split('//')[1].split('/')[0].indexOf(':') > -1 ? files[num].url.split('//')[1].split('/')[0].split(':')[0] : files[num].url.split('//')[1].split('/')[0]
            },
            maxRedirects: 0,
            responseType: 'text',
            data: files[num].f,
            onUploadProgress: function (e) {
              if (e.event.lengthComputable) {
                console.log(parseInt(e.progress * 100))
                currentFile.innerText = files[num].f.name
                currentFileProgress.innerText = '' + parseInt(e.progress * 100) + '%'
              }
            }
          })
          .then( (response) => {
             num++
            console.log(response,num)
            uploadIt(num)
          }).catch(err => {
          alert('文件'+ files[num].f.name+'上传出错。')
            files.length = 0
            num = files.length
          })
    }
</script>
</html>